// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 检查文本是否需要翻译
function shouldTranslateText(text) {
    if (!text) return false;
    text = text.trim();
    if (text.length === 0) return false;
    
    // 跳过纯数字
    if (/^\d+$/.test(text)) return false;
    
    // 跳过URL
    if (/^https?:\/\//.test(text)) return false;
    
    // 跳过邮箱
    if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text)) return false;
    
    return true;
}

// 生成唯一ID
function generateUniqueId() {
    return 'id_' + Math.random().toString(36).substr(2, 9);
}

// 获取元素的绝对位置
function getElementPosition(element) {
    const rect = element.getBoundingClientRect();
    return {
        top: rect.top + window.pageYOffset,
        left: rect.left + window.pageXOffset,
        width: rect.width,
        height: rect.height
    };
}

// 检查元素是否在视口中
function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

// 语言代码映射
const languageMap = {
    'zh': '中文',
    'en': 'English',
    'ja': '日本語',
    'ko': '한국어',
    'fr': 'Français',
    'de': 'Deutsch',
    'es': 'Español',
    'it': 'Italiano',
    'ru': 'Русский',
    'ar': 'العربية'
};

// 获取语言名称
function getLanguageName(code) {
    return languageMap[code] || code;
}

// 存储设置
async function saveSettings(settings) {
    return new Promise((resolve) => {
        chrome.storage.sync.set(settings, resolve);
    });
}

// 获取设置
async function getSettings() {
    return new Promise((resolve) => {
        chrome.storage.sync.get(null, (result) => {
            resolve(result);
        });
    });
}

// 发送消息到背景脚本
async function sendMessageToBackground(message) {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage(message, (response) => {
            resolve(response);
        });
    });
}

// 检测文本语言
function detectLanguage(text) {
    // 简单的语言检测逻辑
    const hasChineseChars = /[\u4e00-\u9fff]/.test(text);
    const hasJapaneseChars = /[\u3040-\u309f\u30a0-\u30ff]/.test(text);
    const hasKoreanChars = /[\u3130-\u318f\uac00-\ud7af]/.test(text);
    
    if (hasChineseChars) return 'zh';
    if (hasJapaneseChars) return 'ja';
    if (hasKoreanChars) return 'ko';
    
    // 默认假设是英文
    return 'en';
}
